using System.Collections.Generic;
using System.Linq;
using DataScripter.Database;
using DataScripter.Scripting;

namespace DataScripter.Sorters
{
    class TableScriptRequestSorterWithForeignKeysFirst : ISorter<ITableScriptRequest>
    {
        private readonly List<ITableScriptRequest> _sortedScriptRequests = new List<ITableScriptRequest>();
        private List<ITableScriptRequest> _allItems;
        public IEnumerable<ITableScriptRequest> Sort(IEnumerable<ITableScriptRequest> items)
        {
            _allItems = items.ToList();
            foreach (ITableScriptRequest scriptRequest in _allItems)
            {
                AddSorted(scriptRequest);
            }
            return _sortedScriptRequests;
        }

        private void AddSorted(ITableScriptRequest scriptRequest)
        {
            if (_sortedScriptRequests.Contains(scriptRequest))
                return;

            foreach (IForeignKey foreignKey in scriptRequest.TableStructure.ForeignKeys)
            {
                AddSorted(_allItems.Single(i => i.TableName == foreignKey.ReferencedTableName));
            }
            _sortedScriptRequests.Add(scriptRequest);
        }

    }
}